package dbinit;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import core.product.model.ProductSearchKey;
import core.util.HibernateCoreUtil;

public class InitProductSearchKey 
{
	@SuppressWarnings("unchecked")
	public static ProductSearchKey getProductSearchKeyByName(String name)
	{
		ProductSearchKey psk = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			List <ProductSearchKey> psks = session.createQuery("from ProductSearchKey psk where psk.searchKey='"+name+"'").list();
			if(psks.size() != 0)
			{
				Iterator<ProductSearchKey> psksItr = psks.iterator() ;
				while(psksItr.hasNext())
				{
					psk = psksItr.next();
					break ;
				}
			}
		
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return psk ;
	}
	
	public static ProductSearchKey getProductSearchKeyByUuid(Long uuid)
	{
		ProductSearchKey psk = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				psk = (ProductSearchKey) session.get(ProductSearchKey.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return psk ;
	}
	public static Long doinit(String searchKey)
	{
		ProductSearchKey productSearchKey = null ;
		productSearchKey = getProductSearchKeyByName(searchKey);
		Long uuid = null;
		if(productSearchKey != null)
		{
			uuid = productSearchKey.getUuid();
		}
		else
		{
			Transaction transaction = null;
			Session session = HibernateCoreUtil.getSessionFactory().openSession();
			productSearchKey = new ProductSearchKey();
			productSearchKey.setSearchKey(searchKey);
			try
			{
				transaction = session.beginTransaction();
				uuid = (Long)session.save(productSearchKey);
				transaction.commit();
			}
			catch(HibernateException he)
			{
				he.printStackTrace();
			}
		}
		return uuid ;
	}
}
